package org.forum.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 实现将文件存至本地，不实现其他数据持久化（进行数据库写入数据）
 * @author One
 *
 */
public class PersistenceUtil {
	
	Logger logger = LoggerFactory.getLogger(PersistenceUtil.class);

	//用户图片存放地址
	private String picturePersistenceUrl;

	public void setPicturePersistenceUrl(String picturePersistenceUrl) {
		this.picturePersistenceUrl = File.separator + picturePersistenceUrl;
	}
	
	//论坛图标存放地址
	private String forumIconPersistenceUrl;
	
	public void setForumIconPersistenceUrl(String forumIconPersistenceUrl) {
		this.forumIconPersistenceUrl = File.separator + forumIconPersistenceUrl;
	}
	/**
	 * 需要持久化的图片需要先存放在List链表中.
	 * @param images
	 * @return
	 */
	public boolean persistPicture(List<File> images, String url){
		if(logger.isDebugEnabled()){
			logger.debug("######################persistPicture#####################");
		}
		File file = null;
		for(int i=0; i<images.size(); i++){
			file = images.get(i);
			try {
				FileInputStream in = new FileInputStream(file);
				File file_native = new File(url);
				FileOutputStream out = new FileOutputStream(file_native);
				byte[] buffer = new byte[1024];
				int len = 0;
				while((len = in.read(buffer))>0){
					out.write(buffer,0,len);
				}
			} catch (FileNotFoundException e) {
				if(logger.isDebugEnabled()){
					logger.debug("文件" + i + " 大小："  + images.size() + "上传错误" + "\n" + e.getMessage());
				}
				return false;
			}catch(IOException ioe){
				if(logger.isDebugEnabled()){
					logger.debug("文件流读取错误.");
				}
				return false;
			}
		}
		return true;
	}
	
}
